#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>
#include "Input.h"
#include "Common/Debug.h"
#include "msgtool.h"

#ifdef _TOUCH_PANEL
#include "TouchPanel.h"
#endif

static int _VirtKey = KEY_NO_DATA;	// last virtual key
extern pid_t UIPID;
extern unsigned char navi_status;

// Initialize the keypad device
int dev_KeyInit(void)
{
	return 1;
}


// Read key data from keypad device
int dev_KeyRead()
{
//Bill semaphore test
	Message qbuf;

	qbuf.mtype = UIPID;
	if(read_message(&qbuf, IPC_NOWAIT))
	{
		if(qbuf.mcommond == MQ_COMMOND_ACTIVE)
		{
			navi_status = 0;
			TestMainInit();//MenuMainInit();//20090105
		}
	}
	return 0;
}

// Read key data from keypad buffer
int dev_KeyReadBuff(void)
{
	int vk;

	vk = _VirtKey;
	_VirtKey = KEY_NO_DATA;

	return vk;
}

// Add a key data to buffer
void dev_KeyAddToBuff(int key)
{
	_VirtKey = key;
}

// Force to clear key buffer
void dev_KeyResetKeyBuff(void)
{

}

int pop_key_buffer(void)
{
	int key;

	key = IRC_NO_KEY;

	return key;
}


/////////////////////////////////////////////////////////////////////////////
// GPS device

static int _gps_fd = -1;

int dev_GpsInit(void)
{
	struct termios options;

	_gps_fd = open("/dev/tts/s0", O_RDWR | O_NOCTTY | O_NDELAY);

	if (_gps_fd == -1)
	{
		LOG("dev_GpsInit: unable to open com port!\n");
		return 0;
	}

	LOG("dev_GpsInit: open com port successfully!\n");

	fcntl(_gps_fd, F_SETFL, 0);

	// set default setting
	tcgetattr(_gps_fd, &options);
	cfsetispeed(&options, B4800);		// B115200 bps
	cfsetospeed(&options, B4800);		// B115200

	options.c_cflag &= ~PARENB;
	options.c_cflag &= ~CSTOPB;
	options.c_cflag &= ~CSIZE;
	options.c_cflag |= CS8;				// n, 8, 1

	// enable checking and stripping of the parity bit
//	options.c_iflag |= (INPCK | ISTRIP);
	// don't do 'Map CR to NL'
	options.c_iflag &= ~ICRNL;

	// disable software flow control
	options.c_iflag &= ~(IXON | IXOFF | IXANY);

	// process hardware flow control, set raw input, 3 second timeout
	options.c_cflag |= CRTSCTS;
	options.c_cflag |= (CLOCAL | CREAD);
	options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
	options.c_oflag &= ~OPOST;
	options.c_cc[VMIN] = 0;
	options.c_cc[VTIME] = 30;
	tcsetattr(_gps_fd, TCSANOW, &options);

	// set default setting - 115200, N, 8, 1
	tcgetattr(_gps_fd, &options);

	LOG("dev_GpsInit: ok\n");

	return 1;
}

int dev_GpsRead(char* pData, int size)
{
	int count;

	if (_gps_fd == -1)
		return 0;

	count = read(_gps_fd, pData, size);		// wait 3 sec for VTIME = 30

	if (count < 0)
	{
		return 0;
	}

	return count;
}

int dev_GpsWrite(char* pData, int size)
{
	int count;

	if (_gps_fd == -1)
		return 0;

	count = write(_gps_fd, pData, size);		// wait 3 sec for VTIME = 30

	if (count < 0)
	{
		return 0;
	}

	return count;
}
